﻿/// 使用OpenCV自带的Codebook函数进行前景检测

#include <cvaux.h>
#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace std;

int main()
{
	IplImage* pFrame = NULL;
	IplImage* pForeground = NULL;
	IplImage* pBackground = NULL;

	int nFrame = 0;
	int nForeground = 0;
	int nUpdateFrame = 30;
	int nClearFrame = 100;

	CvCapture* capture = cvCaptureFromAVI("d:\\10-test\\caviar.avi");

	CvBGCodeBookModel* bgCodebook = cvCreateBGCodeBookModel();

	cvNamedWindow("video",1);
	cvNamedWindow("background",1);
	cvNamedWindow("foreground",1);
	cvMoveWindow("video",30,0);
	cvMoveWindow("background",360,0);
	cvMoveWindow("foreground",690,0);

	while(pFrame = cvQueryFrame(capture))
	{
		nFrame++;
		if(nFrame == 1)
		{
			pBackground = cvCreateImage(cvGetSize(pFrame),8,3);
			pForeground = cvCreateImage(cvGetSize(pFrame),8,1);

			cvCvtColor(pFrame,pBackground,CV_BGR2YCrCb);
			cvBGCodeBookUpdate(bgCodebook,pBackground);
		}
		else
		{
			cvCvtColor(pFrame,pBackground,CV_BGR2YCrCb);
			if(nFrame%nUpdateFrame == 0)
				cvBGCodeBookUpdate(bgCodebook,pBackground);
			if(nFrame%nClearFrame == 0)
				cvBGCodeBookClearStale(bgCodebook,bgCodebook->t/2);

			cvSet(pForeground,cvScalar(255));
			cvBGCodeBookDiff(bgCodebook,pBackground,pForeground);
			cvSegmentFGMask(pForeground);

			cvShowImage("video",pFrame);
			cvShowImage("background",pBackground);
			cvShowImage("foreground",pForeground);
			cout << nForeground << endl;
			if(cvWaitKey(10) >= 0)
				break;
		}
	}
	cvReleaseBGCodeBookModel(&bgCodebook);
	cvDestroyAllWindows();
	cvReleaseImage(&pForeground);
	cvReleaseImage(&pBackground);
	cvReleaseCapture(&capture);

	return 0;
}